package im.starchat.chat.view;

import android.graphics.Bitmap;
import android.graphics.BitmapShader;
import android.graphics.Canvas;
import android.graphics.ColorFilter;
import android.graphics.Paint;
import android.graphics.PixelFormat;
import android.graphics.Rect;
import android.graphics.Shader;
import android.graphics.drawable.Drawable;

public class RoundDrawable extends Drawable{

    Bitmap mOriBitmap;
    boolean mIsCircle = true;
    int mCornerX;
    int mCornerY;
    int mWidth;
    int mHeight;
    Paint mBitmapPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
    float mSx = 1.0f;
    float mSy = 1.0f;

    public RoundDrawable(Bitmap bitmap) {
        if (bitmap == null) {
            throw new IllegalArgumentException("params bitmap should not be null!");
        }
        mOriBitmap =  bitmap;
        BitmapShader shader = new BitmapShader(mOriBitmap, Shader.TileMode.CLAMP
                , Shader.TileMode.CLAMP);
        mBitmapPaint.setShader(shader);
    }

    public void setIsCircle(boolean isCircle) {
        if (isCircle == mIsCircle) {
            return;
        }
        mIsCircle = isCircle;
        invalidateSelf();
    }

    public void setCornerSize(int cornerX, int cornerY) {
        if (cornerX == mCornerX && cornerY == mCornerY) {
            return;
        }
        mCornerX = cornerX;
        mCornerY = cornerY;
        invalidateSelf();
    }

    @Override
    public int getIntrinsicWidth() {
        if (mOriBitmap != null) {
            return mOriBitmap.getWidth();
        }
        return super.getIntrinsicWidth();
    }

    @Override
    public int getIntrinsicHeight() {
        if (mOriBitmap != null) {
            return mOriBitmap.getHeight();
        }
        return super.getIntrinsicHeight();
    }

    @Override
    protected void onBoundsChange(Rect bounds) {
        super.onBoundsChange(bounds);
        mWidth = bounds.width();
        mHeight = bounds.height();
        mSx = mWidth * 1.0f / mOriBitmap.getWidth();
        mSy = mHeight * 1.0f / mOriBitmap.getHeight();
    }

    @Override
    public void draw(Canvas canvas) {
        if (mOriBitmap == null) {
            return;
        }
        canvas.save();
        canvas.scale(mSx, mSy);
        if (mIsCircle) {
            canvas.drawCircle(mWidth / 2, mHeight / 2, Math.min(mWidth, mHeight) / 2,  mBitmapPaint);
        } else {

        }
        canvas.restore();
    }

    @Override
    public void setAlpha(int alpha) {

    }

    @Override
    public void setColorFilter(ColorFilter colorFilter) {

    }

    @Override
    public int getOpacity() {
        return PixelFormat.TRANSLUCENT;
    }
}
